﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Entity;
using System.Data.Objects;
using Entity;

namespace School.SystemManage
{
    public partial class login : BasePage
    {
        TechnologySchoolEntities db = new TechnologySchoolEntities(); 

        protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        protected void btn_Submit_Click(object sender, ImageClickEventArgs e)
        {
            if (this.chknumber.Text.ToUpper() != GetCookie("CheckCode"))
            {
                lblMsg.Text = "验证码错误！";
                return;
            }

            try
            {
                string userName = user.Text.Trim();
                string userPwd = Security.Cryptography.AESEncrypt(pwd.Text.Trim(), "technology");

                var loginuser = (from u in db.AdminUsers
                                 where u.UserName == userName && u.UserPwd == userPwd
                                 select new
                                 {
                                     u.UserID,
                                     u.Role,
                                     u.LoginTime
                                 }).FirstOrDefault();
                              
                if (loginuser != null)
                {
                    db.AdminUsers.FirstOrDefault(a=>a.UserID==loginuser.UserID).LoginTime = DateTime.Now;
                    db.SaveChanges();

                    AddCookie("UserLoginName", Security.Cryptography.DESEncrypt(user.Text.Trim(), "KYLECHEN"));
                    AddCookie("UserLoginID", loginuser.UserID.ToString());
                    AddCookie("UserRole", Security.Cryptography.DESEncrypt(loginuser.Role.RoleName, "KYLECHEN"));
                    AddCookie("UserRoleID", Security.Cryptography.DESEncrypt(loginuser.Role.RID.ToString(), "KYLECHEN"));
                    AddCookie("UserRoleAction", loginuser.Role.Action);
                    Response.Redirect("~/SystemManage/main.aspx");
                }
                else
                {
                    lblMsg.Text = "用户不存在或密码错误";
                }
            }
            catch (Exception ex)
            {
                lblMsg.Text = "发生异常，原因：" + ex.Message;
            }
                                 
        }
    }
}
